package com.yixing.tech.common.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.MongoTransactionManager;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.convert.MongoCustomConversions;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Configuration
public class TransactionConfig {

    @Resource
    MongoDatabaseFactory mongoDatabaseFactory;

    @Bean
    @ConditionalOnProperty(name = "spring.data.mongodb.transactionEnabled", havingValue = "true")
    MongoTransactionManager transactionManager(MongoDatabaseFactory mongoDatabaseFactory) {
        return new MongoTransactionManager(mongoDatabaseFactory);
    }


//    @Bean
//    @Primary
//    @ConfigurationProperties(prefix = "spring.data.mongodb")
//    public MongoProperties primaryMongoProperties() {
//        return new MongoProperties();
//    }
//
//    @Primary
//    @Bean(name = "mongoDatabaseFactory")
//    public MongoDatabaseFactory primaryFactory(MongoProperties mongoProperties) {
//        return new SimpleMongoClientDatabaseFactory(mongoProperties.getUri());
//    }


    @Primary
    @Bean(name = "mongoTemplate")
    public MongoTemplate getMongoTemplate(MongoDatabaseFactory mongoDatabaseFactory) {
        MongoTemplate mongoTemplate = new MongoTemplate(mongoDatabaseFactory);
        // 获取mongo类型转换器
        MappingMongoConverter mongoMapping = (MappingMongoConverter) mongoTemplate.getConverter();
        // set 自定义转换器
        mongoMapping.setCustomConversions(customConverter());
        //不插入_class
        mongoMapping.setTypeMapper(new DefaultMongoTypeMapper(null));
        mongoMapping.afterPropertiesSet();
        return mongoTemplate;
    }

    @Bean
    public MongoCustomConversions customConverter() {
        List<Converter<?, ?>> converters = new ArrayList<>();
        converters.add(new DocumentToDocumentConverter());
        return new MongoCustomConversions(converters);
    }
}
